package com.ppch.wuwamanus.rag;

import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetriever;
import com.alibaba.cloud.ai.dashscope.rag.DashScopeDocumentRetrieverOptions;
import org.springframework.ai.chat.client.advisor.RetrievalAugmentationAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.rag.generation.augmentation.ContextualQueryAugmenter;
import org.springframework.ai.rag.preretrieval.query.transformation.QueryTransformer;
import org.springframework.ai.rag.preretrieval.query.transformation.RewriteQueryTransformer;
import org.springframework.ai.rag.retrieval.search.DocumentRetriever;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Package:com.ppch.wuwamanus.rag
 * ClassName:DashScopeRetrievalAugmentationAdvisorConfig
 *
 * @Author 泡泡茶壶
 * @Create 2025/7/9 22:26
 * @Version 1.0
 * Description:
 *  初始化基于云知识库（阿里云百炼）的检索增强顾问 RetrievalAugmentationAdvisor
 */
@Configuration
public class DashScopeRetrievalAugmentationAdvisorConfig {

    @Value("${spring.ai.dashscope.api-key}")
    private String DashScope_Api_Key;

    /**
     * 初始化基于云知识库（阿里云百炼）的检索增强顾问 RetrievalAugmentationAdvisor
     * @return RetrievalAugmentationAdvisor
     */
    @Bean
    public Advisor dashScopeRetrievalAugmentationAdvisor(){
        //1.通过api-key创建 DashScopeApi
        DashScopeApi dashScopeApi = new DashScopeApi(DashScope_Api_Key);
        //2.云知识库的名称
        String cloudKnowledgeRepositoryName =  "《鸣潮》WIKI";
        //3.创建 文档检索器 DocumentRetriever
        DocumentRetriever dashScopeDocumentRetriever = new DashScopeDocumentRetriever(dashScopeApi,
                DashScopeDocumentRetrieverOptions.builder()
                        //云知识库名称
                        .withIndexName(cloudKnowledgeRepositoryName)
                        //返回的检索文档数量
                        .withRerankTopN(5)
                        //最小相似度阈值
                        .withRerankMinScore(0.5f)
                        .build());
        //4.创建 上下文查询增强器 ContextualQueryAugmenter
        ContextualQueryAugmenter contextualQueryAugmenter = new MyContextualQueryAugmenter()
                .createContextualQueryAugmenter(" 你应该输出下面的内容： " +
                        "抱歉，您的问题已超出知识库范围，暂时无法回答。", true);
        //5.创建 RetrievalAugmentationAdvisor 检索增强顾问
        return RetrievalAugmentationAdvisor.builder()
                .documentRetriever(dashScopeDocumentRetriever)
                .queryAugmenter(contextualQueryAugmenter)
                .build();
    }
}
